﻿<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Version Check Page</title>
<link rel="stylesheet" type="text/css" href="${make_url('/static/app/launcher/application.css')}"  media="screen" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />

<%!
   from splunk.entity import buildEndpoint
   from splunk import rest
   from splunk import getDefault, auth
   from mako import exceptions
   import splunk
   import os
   import logging
   import urllib
   import cherrypy
   import splunk.bundle as bundle
   import json

   def convert_spaces_to_underscores(s):
      
      if s:
         new_id = ''

         #remove . : ( ) chars as well
         for e in s:
            if e.isalpha() or e.isdigit() or s.isspace():
               new_id += e
         #ensure it starts with a char
         if not new_id[0].isalpha():
            new_id = 'a'+new_id

         return '_'.join(new_id.split(' ')).strip()

   def quote_strings_for_javascript(s, max_length = 14000, unicode=True): 
       ret = [] 

       # Try to split on whitespace, not in the middle of a word. 
       split_at_space_pos = max_length - 10 
       if split_at_space_pos < 10: 
           split_at_space_pos = None 

       position = 0 
#       if unicode: 
#           position += 1 
#           ret.append('L') 

       ret.append('"') 
       position += 1 
       for c in s: 
           newline = False 
           if c == "\n": 
               to_add = "\\\n" 
               newline = True 
           elif ord(c) < 32 or 0x80 <= ord(c) <= 0xff: 
               to_add = "\\x%02x" % ord(c) 
           elif ord(c) > 0xff: 
               if not unicode: 
                   raise ValueError, "string contains unicode character but unicode=False" 
               to_add = "\\u%04x" % ord(c) 
           elif '\\"'.find(c) != -1: 
               to_add = "\\%c" % c 
           else: 
               to_add = c 

           ret.append(to_add) 
           position += len(to_add) 
           if newline: 
               position = 0 

           if split_at_space_pos is not None and position >= split_at_space_pos and " \t".find(c) != -1: 
               ret.append("\\\n") 
               position = 0 
           elif position >= max_length: 
               ret.append("\\\n") 
               position = 0 

       ret.append('"') 

       return "".join(ret) 

   # pull app name out of URL
   # e.g. http://localhost:8000/en-US/app/splunkwas/checkversion
   # TODO: replace this with a future-friendly version
   def getCurrentApp():
       segments = cherrypy.request.path_info.split ('/', 4)
       return segments[3]

   def get_app_version():
       try:
           rawConfig = bundle.getConf('app', sessionKey=splunk.getSessionKey(), namespace=getCurrentApp())
       except splunk.ResourceNotFound:
           return None
       return rawConfig['launcher'].get('version', 1.0)

   logger = logging.getLogger('splunk.apps.' + getCurrentApp())

%>

<%

    namespace = 'launcher'
    sessionId = cherrypy.session.id
    sb_uri = make_url('/manager/%s/%s' % (namespace, 'apps/remote'))
   
    sburi = buildEndpoint('apps/remote', entityName='entries')
    net_is_down_flag = False

    splunk_version = cherrypy.config['version_number']
    if '.' not in splunk_version:
        splunk_version = '4.99.0'

    try:
        sbserverResponse, sbserverContent = rest.simpleRequest(sburi, sessionKey=splunk.getSessionKey(), getargs={'sort_by':'downloads', 'count':'1000', 'splunk_version':splunk_version}, timeout=10)
    except Exception, e:
        sbatom = []
        net_is_down_flag = True
        logger.error(str(e))
    else:
        if sbserverResponse.status == 200:
            sbatom = rest.format.parseFeedDocument(sbserverContent)
        else:
            sbatom = []
            net_is_down_flag = True

%>

<script type="text/javascript">
function performInstall(num) {
    var form = $("#install_form_" + num);
    form.find("input[name=splunk_session_id]").val(jQuery.cookie('session_id_' + Splunk.util.getConfigValue('MRSPARKLE_PORT_NUMBER')));
    form.submit();
    form.find("input[name=splunk_session_id]").val('');
    return true;
}

function clickInstall(appName, num) {
    % if 'sbSessionKey' in cherrypy.session:
        $("#loading").show();      
        performInstall(num);
    % else:
        var popup = new Splunk.Popup($('.loginForm'), {
           title : ${jsonify(_("Login"))},
           pclass : "myPopupClass",
           buttons : [
               {
                   label: ${jsonify(_('Cancel'))},
                   type : 'secondary',
                   callback: function(){
                       return true;
                   }.bind(this)
               },
               {
                   label: ${jsonify(_('Login'))},
                   type : 'primary',
                   callback: function(){
                       $('.error').html('');
                        
                       $.post(
                            '${sb_uri}/login',
                            {
                                username: $('#sbuser').val(),
                                password: $('#sbpass').val()
                            },
                            function(data) {
                                if(data != '') {
                                    $("#loading").show();
                                    performInstall(num);
                                    return true; 
                                }
                                else {
                                    $('.error').html(${jsonify(_('Invalid username or password.'))});
                                }
                            }
                        );
                       
                   }.bind(this)
               }
           ]
        });
    % endif
}


</script> 
    
<% 
appsList = []
for sbentry in sbatom:
    sbparsedRawContents = rest.format.nodeToPrimitive(sbentry.rawcontents)
    listEntry = {'rawContents':sbparsedRawContents, 'title': sbentry.title, 'summary':sbentry.summary, 'id':sbentry.id, 'updated': sbentry.updated.ctime()}
    appsList.append (listEntry)
%>
<script type="text/javascript">

// script to load apps list (e.g. for update checks)
var appsList = 
${ json.dumps (appsList, indent=2) }
;

function checkForNewVersion (unescapedSplunkbaseTitle, currentVersion) 
{
    if (!appsList || !unescapedSplunkbaseTitle || !currentVersion)
        return null;

    for (var i = 0; i < appsList.length; i++)
    {
        if (appsList[i].title.toLowerCase() == unescapedSplunkbaseTitle.toLowerCase())
        {
            var latestVersion = appsList[i].rawContents['latestVersion'];
            if (latestVersion == currentVersion)
                return null;    // no version update
            else
                return appsList[i]; // version update!
        }
    }
    return null;
}

function getCurrentAppVersion()
{
    return '${get_app_version()}';
}

</script>

<!-- Current App's version is ${get_app_version()} -->    

</head>

<body>
	   % if net_is_down_flag :
	       <div class="noSplunkbase">
	           <h3>
                   ${_("Launcher can't connect to the Internet. Visit splunkbase.com to find and download Splunk apps.")}
               </h3>    
           </div>  
	   % else : 
       
    <div class="loginForm" style="display: none; padding:10px;">
        <form class="appLogin">
            <div class="adminFormSection">
                <div class="adminFormItem">
                    <h2>${_('Login to Splunk.com to download apps.')}</h2>
                </div>
                <p class="error"></p>
                <div class="adminFormItem">
                    <label><%doc>TRANS: Username prompt</%doc>${_('Username')}</label>
                    <input value="" size="30" id="sbuser" type="text">
                </div>
                
                <div class="adminFormItem">
                    <label><%doc>TRANS: Password prompt</%doc>${_('Password')}</label>
                    <input size="30" id="sbpass" type="password">
                </div>

                <div class="adminFormItem" style="text-align:right; margin-top:10px;">
                    <a href="http://www.splunk.com/?module=roles&func=lostpassword" target="_blank">${_('Forgot your password?')}</a>
                </div>

            </div>
            <br><br>
        </form>
    </div>    

    <% i=0 %>
    % for sbentry in sbatom:
            
        <% 
            sbparsedRawContents = rest.format.nodeToPrimitive(sbentry.rawcontents) 
                    
            try:
                sbdesc = sbentry.summary
            except (KeyError, AttributeError):
                sbdesc = _('No description has been provided for this app. Please update app.conf for your app.')
                                        
            try:
                sbversion = sbparsedRawContents['latestVersion'] 
            except (KeyError, AttributeError): 
                sbversion = '1.0'
                    
            try:
                sbauthor = sbparsedRawContents['author']
            except (KeyError, AttributeError):                                                              
                sbauthor = 'Splunk'
                
        %>
<div class="appsApplicationBox" id="${convert_spaces_to_underscores(sbentry.title)}MenuSB">

<div class="appDetail">
<div class="splunkBaseAppTitle">${sbentry.title}</div>
<div class="clear"></div>
<table class="appDetailsTable"><tbody><tr>
    <th>${_('Author:')}</th><td>${sbauthor}</td>
    <%
        import time
        timestamp = sbparsedRawContents['dateAddonUpdated']
        ts = time.strptime(timestamp[:19], "%Y-%m-%dT%H:%M:%S")
        newTimestamp = time.strftime("%m/%d/%Y %H:%M:%S", ts)
    %>
    <th>${_('Updated:')}</th><td>${newTimestamp}</td>
    <th>${_('Version:')}</th><td>${sbparsedRawContents['latestVersion']}</td>
    <td>
        <div class="buttonDiv">

            % if sbparsedRawContents['price'] is not None and 'free' in sbparsedRawContents['price'].lower():
    
            <form id="install_form_${i}" action="${sb_uri}" method="post">
                <input name="splunk_session_id" type="hidden">
                <input value="install" name="action" type="hidden">
                <input value="${urllib.quote_plus(sbentry.title)}" name="encodedAppname" type="hidden">
            </form>  
                            
            <button class="splButton-primary" onclick="clickInstall('${sbentry.title}', '${i}');">
                <span>${_('Install Free')}</span>
            </button>

            % else :

            <div class="button">
                <a href="${sbparsedRawContents['appURL']}" target="_blank" class="splButton-primary"><span>${_('App Details')}</span></a>
            </div>

            % endif 
        </div>
    </td>
</tr></tbody></table>
</div>
<div class="clear"></div>
</div>
            <% i=i+1 %>
            % endfor

        % endif

</body>
</html>




